import json
import os
import datetime
import base64

import cv2
import requests
from ultralytics import YOLO

import uuid

os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'

# model = YOLO("./runs/detect/train/weights/best.pt")
model = YOLO("fall_det_1.pt")

video_path = "video.mp4"
cap = cv2.VideoCapture(video_path)

window_name = "My Window"
cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)  # 创建可调整大小的窗口
cv2.resizeWindow(window_name, 730, 400)  # 设置窗口大小为 800x600

count = 0
countnofail = 0
req_id = uuid.uuid4()
# Loop through the video frames
while cap.isOpened():
    # Read a frame from the video
    success, frame = cap.read()

    if success:
        # Run YOLOv8 tracking on the frame, persisting tracks between frames
        results = model.track(frame, persist=True, conf=0.5)

        # Visualize the results on the frame
        annotated_frame = results[0].plot()

        # Display the annotated frame
        cv2.imshow(window_name, annotated_frame)

        res = results[0]
        if res.boxes is not None:
            boxes = res.boxes
            if boxes.cls is not None:
                cls = boxes.cls
                for i in range(len(cls)):
                    if cls[i] == 0:
                        if count == 0:
                            # 获取当前时间
                            current_time = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
                            
                            # 将图片转换为base64
                            _, buffer = cv2.imencode('.jpg', frame)
                            base64_image = base64.b64encode(buffer).decode('utf-8')
                            
                            data = {
                                "imageUrls": base64_image,
                                "reqId": str(req_id)
                            }
                            
                            #调用post接口 如果摔倒
                            post_headers = {'Content-Type': 'application/json', "Accept": "*/*"}
                            r = requests.post('http://localhost:8080/system/elderlyFallRecord/fall', data=json.dumps(data),
                                          headers=post_headers)
                        count += 1
                        print("Fall detected")
                    else:
                        count = 0
                        if countnofail == 0:
                            data = {
                                "reqId": str(req_id)
                            }

                            # 调用post接口 如果摔倒
                            post_headers = {'Content-Type': 'application/json', "Accept": "*/*"}
                            r = requests.post('http://localhost:8080/system/elderlyFallRecord/end',
                                              data=json.dumps(data),
                                              headers=post_headers)
                        count += 1
                        print("No fall detected")

        # Break the loop if 'q' is pressed
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        # Break the loop if the end of the video is reached
        break

# Release the video capture object and close the display window
cap.release()
cv2.destroyAllWindows()
if count != 0:
    data = {
        "reqId": str(req_id)
    }

    # 调用post接口 如果摔倒
    post_headers = {'Content-Type': 'application/json', "Accept": "*/*"}
    r = requests.post('http://localhost:8080/system/elderlyFallRecord/end', data=json.dumps(data),
                      headers=post_headers)
print(count) 